<template>
  <div
    ref="editorWrapperRef"
    class="wang-editor-container"
    :style="{
      'border-color': isFocus
        ? 'var(--el-color-primary)'
        : 'var(--el-border-color)',
    }"
  >
    <div ref="toolbarRef" class="toolbar-container"></div>
    <div
      ref="editorRef"
      class="editor-container"
      :style="{ height: editorHeight + 'px', width: '100%' }"
    ></div>
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { ref, onMounted, onBeforeUnmount } from "vue";
import { createEditor, createToolbar, Boot } from "@wangeditor/editor";
import attachmentModule from "@wangeditor/plugin-upload-attachment";

const props = defineProps({
  modelValue: { type: String, default: "", required: true },
  placeholder: { type: String, default: "请输入内容..." },
  editorHeight: { type: Number, default: 300 },
  editorConfig: { type: Object, default: {} },
  toolbarConfig: { type: Object, default: {} },
});

const emit = defineEmits(["update:modelValue", "change"]);

const isFocus = ref(false);
const editorWrapperRef = ref(null);
const toolbarRef = ref(null);
const editorRef = ref(null);
let editorInstance = null;
let toolbarInstance = null;

const initEditor = () => {
  if (!editorRef.value || !toolbarRef.value) return;

  // 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
  if (Boot.plugins.length < 13) {
    //判断如果已经插入进去，不在二次插入
    Boot.registerModule(attachmentModule);
  }

  /**
   *  编辑器配置
   * */
  const editorConfig = {
    placeholder: props.placeholder,
    onChange(editor) {
      emit("update:modelValue", editor.getHtml());
    },
    onFocus() {
      isFocus.value = true;
    },
    onBlur() {
      isFocus.value = false;
    },
    // 其他配置...
    ...props.editorConfig,
    MENU_CONF: {
      // 本地图片上传
      uploadImage: {
        // 最多可上传几个文件，默认为 100
        maxNumberOfFiles: 1,
        // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
        allowedFileTypes: ["image/*"],
        // 自定义上传
        async customUpload(file, insertFn) {
          if (!file.type.includes("image")) {
            return proxy.$modal.msgError("请上传图片格式的文件");
          }
          if (file.size / 1024 / 1024 > 200) {
            return proxy.$modal.msgError("请上传200M以内的图片！");
          }

          const reader = new FileReader();
          reader.onload = (e) => {
            const base64 = e.target.result;
            // 最后插入图片
            insertFn(base64, "图片描述", "alt", "href");
          };
          reader.readAsDataURL(file);
        },
      },
      // 本地视频上传
      uploadVideo: {
        async customUpload(file, insertFn) {
          // console.log(file, "customUpload");
          if (!file.type.includes("video")) {
            return proxy.$modal.msgError("请上传视频格式的文件！");
          } else if (file.size / 1024 / 1024 > 200) {
            return proxy.$modal.msgError("请上传200M以内的文件！");
          }
          // const formData = new FormData();
          // formData.append("file", file);
        },
      },
      // 附件上传
      uploadAttachment: {
        async customUpload(file, insertFn) {
          console.log(file, "uploadAttachment");
          if (file.size / 1024 / 1024 > 200) {
            return proxy.$modal.msgError("请上传200M以内的附件！");
          }
          // const formData = new FormData();
          // formData.append("file", file);
        },
      },
    },
  };

  editorInstance = createEditor({
    selector: editorRef.value,
    html: props.modelValue,
    config: editorConfig,
  });

  /**
   *  工具栏配置
   * */
  const toolbarConfig = {
    // 其他配置...
    ...props.toolbarConfig,
    insertKeys: {
      index: 24, // 自定义插入的位置
      keys: ["uploadAttachment", "|"], // “上传附件”菜单
    },
  };
  toolbarInstance = createToolbar({
    selector: toolbarRef.value,
    editor: editorInstance,
    config: toolbarConfig,
  });
};

onMounted(() => {
  initEditor();
});

onBeforeUnmount(() => {
  if (editorInstance) {
    editorInstance.destroy();
  }
});
</script>

<style lang="scss" scoped>
.wang-editor-container {
  width: 100%;
  border: 1px solid var(--el-border-color); /* --el-border-color: #dcdfe6 */
  border-radius: var(--el-border-radius-base); /* --el-border-color: 4px */
  box-sizing: border-box;
  overflow: hidden;

  &.w-e-full-screen-container {
    z-index: 1;
  }
  :deep() {
    .toolbar-container {
      width: 100%;
      border-bottom: 1px solid var(--el-border-color);
      box-sizing: border-box;
    }
    .editor-container {
      width: 100%;
      overflow-y: hidden;
      .w-e-text-placeholder {
        top: 10px !important;
      }
    }
  }
}
</style>